package com.baidu.ueditor.upload;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import com.cms.support.QiniuFileUtil;

public class BinaryUploader {

	public static final State save(HttpServletRequest request,
			Map<String, Object> conf) {
		boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;

		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}

		ServletFileUpload upload = new ServletFileUpload(
				new DiskFileItemFactory());

		if (isAjaxUpload) {
			upload.setHeaderEncoding("UTF-8");
		}

		MultipartResolver resolver = new CommonsMultipartResolver(request
				.getSession().getServletContext());
		MultipartHttpServletRequest multipartRequest = resolver
				.resolveMultipart(request);
		CommonsMultipartFile orginalFile = (CommonsMultipartFile) multipartRequest
				.getFile("upfile");

		if (orginalFile == null) {
			return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
		}

		String originFileName = orginalFile.getOriginalFilename();
		String suffix = FileType.getSuffixByFilename(originFileName);

		originFileName = originFileName.substring(0, originFileName.length()
				- suffix.length());

		long maxSize = ((Long) conf.get("maxSize")).longValue();
		if (orginalFile.getSize() > maxSize) {
			return new BaseState(false, AppInfo.MAX_SIZE);
		}

		if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
			return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
		}

		State storageState = new BaseState(true);
		try {
			String url = QiniuFileUtil.upload(orginalFile);
			storageState.putInfo("size", orginalFile.getSize());
			storageState.putInfo("title", originFileName);
			storageState.putInfo("url", url);
			storageState.putInfo("type", suffix);
			storageState.putInfo("original", originFileName + suffix);
		} catch (Exception e) {
			return new BaseState(false, AppInfo.IO_ERROR);
		}

		return storageState;
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
